package de.slothsoft.network;

import java.io.IOException;
import java.net.Socket;

public class BroadcastingServer extends Server {

	public BroadcastingServer(int port) throws NetworkException {
		super(port);
	}

	@Override
	protected ServerClient createClient(Socket socket) throws NetworkException {
		ServerClient client = super.createClient(socket);
		client.addClientListener(new ClientAdapter() {

			@Override
			public void receivedObject(ClientEvent event) {
				try {
					broadcastObject(event.getSource(), event.getIncomingObject());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		return client;
	}

	protected void broadcastObject(Client source, Object object) throws IOException {
		Client[] clientArray = getConnectedClients().toArray(new Client[0]);
		for (Client client : clientArray) {
			if (source != client) {
				client.getOutputStream().writeObject(object);
			}
		}
	}
}
